package com.qf.controller;

import com.qf.entity.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.security.auth.login.CredentialException;

@RestController
public class UserController {
    @RequestMapping("/logout")
    public Result logout(){
        //获取登录的主体对象
        Subject subject = SecurityUtils.getSubject();
        //执行退出功能
        subject.logout();
        return new Result(0,"退出成功");
    }
    @RequestMapping("/doLogin")
    public Result login(String username, String password,Boolean rememberMe){
        //获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //创建token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        if (rememberMe!=null && rememberMe){
            token.setRememberMe(true);
        }
        //调用登录功能，执行realm，在realm当中获取用户，角色，权限信息
        try {
            subject.login(token);
            //判断角色
            System.out.println("管理员角色："+subject.hasRole("管理员"));
            //判断权限
            System.out.println("新增用户的权限："+subject.isPermitted("sys:user:add"));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new Result(1,"未知的账户信息");
        } catch (LockedAccountException e) {
            e.printStackTrace();
            return new Result(1,"账户已锁定");
        } catch (CredentialsException e) {
            e.printStackTrace();
            return new Result(1,"密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new Result(1,"其他认证问题");
        }
        if (subject.isAuthenticated()){
            System.out.println("登录成功");
        }
        return new Result(0,"登录成功");
    }
}
